package com.micangcaihang.common.loader;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;

import static com.bumptech.glide.Glide.with;

/**
 * @Description: 使用Glide框架加载图片
 */
public class GlideLoader implements ILoader {
    @Override
    public void init(Context context) {
        try {
            Class.forName("com.bumptech.glide.Glide");
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Must be dependencies Glide!");
        }
    }

    @Override
    public void loadNet(ImageView target, String url, Options options) {
        load(getRequestManager(target.getContext()).load(url), target, options);
    }

    @Override
    public void loadResource(ImageView target, int resId, Options options) {
        load(getRequestManager(target.getContext()).load(resId), target, options);
    }

    @Override
    public void loadAssets(ImageView target, String assetName, Options options) {
        load(getRequestManager(target.getContext()).load("file:///android_asset/" + assetName), target, options);
    }

    @Override
    public void loadFile(ImageView target, File file, Options options) {
        load(getRequestManager(target.getContext()).load(file), target, options);
    }

    @Override
    public void clearMemoryCache(Context context) {
        Glide.get(context).clearMemory();
    }

    @Override
    public void clearDiskCache(Context context) {
        Glide.get(context).clearDiskCache();
    }

    private RequestManager getRequestManager(Context context) {
        return with(context);
    }

    private void load(RequestBuilder<Drawable> manager, ImageView target, Options options) {
        if (options == null) options = Options.defaultOptions();
        RequestOptions glideOption = new RequestOptions();
        glideOption.diskCacheStrategy(DiskCacheStrategy.ALL);
        if (options.loadingResId != Options.RES_NONE) {
            glideOption.placeholder(options.loadingResId);
        }
        if (options.loadErrorResId != Options.RES_NONE) {
            glideOption.error(options.loadErrorResId);
        }
        if (options.width != 0 && options.height != 0) {
            glideOption.override(options.width, options.height);
        }
        switch (options.cacheType) {
            case 0:
                glideOption.diskCacheStrategy(DiskCacheStrategy.ALL);
                break;
        }
        glideOption.dontAnimate();
        manager.apply(glideOption)
                .into(target);
    }
}
